import os
from dashscope import Generation


def get_response(messages):
    response = Generation.call(
        # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key="sk-xxx",
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        model="qwen-plus",
        messages=messages,
        result_format="message",
    )
    return response


def main():
    messages = [
        {
            "role": "system",
            "content": """你是一名AI助手。""",
        }
    ]

    while True:
        user_input = input("请输入：")
        if "退出" in user_input:
            break
        # 将用户问题信息添加到messages列表中
        messages.append({"role": "user", "content": user_input})
        response = get_response(messages)
        if response.status_code != 200:
            print(f"API调用失败，错误信息：{response.message}")
            break
        assistant_output = response.output.choices[0].message.content
        # 将大模型的回复信息添加到messages列表中
        messages.append({"role": "assistant", "content": assistant_output})
        print(f"模型输出：{assistant_output}")
        print("\n")


if __name__ == "__main__":
    main()
